<template>
  <div id="app">
    <div class="container">
      <div class="sidebar">
        <div class="profile">
          <div class="avatar-container">
            <el-upload class="avatar-uploader" action="" :show-file-list="false" :auto-upload="false"
              :on-change="handleAvatarUpload" accept="image/*">
              <div class="avatar-box">
                <el-avatar :size="50" :src="avatarUrl" class="avatar" v-if="user.avatar" />
                <div class="avatar-hover">更换头像</div>
              </div>
            </el-upload>
          </div>
          <div class="info">
            <h2 class="username">{{ user.realName }}</h2>
            <p class="motto">个签：{{ user.signature }}</p>
          </div>
        </div>
        <div class="custom-menu">
          <div :class="['menu-btn', { active: activeMenu === 'community' }]" @click="selectMenu('community')">主页</div>
          <div :class="['menu-btn', { active: activeMenu === 'ability' }]" @click="selectMenu('ability')">面试能力</div>
          <div :class="['menu-btn', { active: activeMenu === 'resume' }]" @click="selectMenu('resume')">我的简历</div>
          <!-- 我的简历子菜单 -->
          <div v-if="activeMenu === 'resume'" v-for="item in resumeSubTabs" :key="item.name"
            :class="['sub-btn', { active: resumeView === item.name }]" @click="resumeView = item.name">{{
              item.label
            }}</div>
          <div :class="['menu-btn', { active: activeMenu === 'communityview' }]" @click="selectMenu('communityview')">社区
          </div>
          <!-- 新增：知识库菜单 -->
          <div :class="['menu-btn', { active: activeMenu === 'knowledge' }]" @click="selectMenu('knowledge')">知识库</div>
          <!-- 知识库子菜单 -->
          <div v-if="activeMenu === 'knowledge'" v-for="item in knowledgeSubTabs" :key="item.name"
            :class="['sub-btn', { active: knowledgeView === item.name }]" @click="knowledgeView = item.name">{{
              item.label
            }}</div>

          <!-- 新增：我的收藏菜单 -->
          <div :class="['menu-btn', { active: activeMenu === 'collection' }]" @click="selectMenu('collection')">我的收藏
          </div>
          <!-- 我的收藏子菜单 -->
          <div v-if="activeMenu === 'collection'" v-for="item in collectionSubTabs" :key="item.name"
            :class="['sub-btn', { active: collectionView === item.name }]" @click="collectionView = item.name">{{
              item.label }}</div>

          <div :class="['menu-btn', { active: activeMenu === 'record' }]" @click="selectMenu('record')">面试记录</div>
          <div :class="['menu-btn', { active: activeMenu === 'schedule' }]" @click="selectMenu('schedule')">面试安排</div>
          <div :class="['menu-btn', { active: activeMenu === 'account' }]" @click="selectMenu('account')">账号设置</div>
        </div>
        <div class="task-recommend">
        </div>
      </div>

      <!-- 中间内容区域 -->
      <div class="main-content">
        <!-- 默认显示 MainContent -->
        <MainContent v-if="activeMenu === 'community'" />

        <!-- 面试能力 -->
        <InterviewAbility v-if="activeMenu === 'ability'" />

        <!-- 我的简历 -->
        <div v-show="activeMenu === 'resume'">
          <div v-show="resumeView === 'resume-sdk'">
            <!-- <ResumeSDK /> -->
            <ResumeSDK v-show="resumeView === 'resume-sdk'" :resume-data="resumeSDKData"
              :resume-paint="resumeSDKPaint" />
            <!-- 这里放简历解析组件 -->
          </div>
          <div v-if="resumeView === 'resume-manage'">
            <ResumeList />
          </div>
        </div>

        <div v-if="activeMenu === 'communityview'">
          <Community />
        </div>

        <!-- 新增：知识库菜单内容 -->
        <div v-if="activeMenu === 'knowledge'">
          <div v-if="knowledgeView === 'personal-knowledge'">
            <KnowledgeBase />
          </div>
          <div v-if="knowledgeView === 'community-knowledge'">
            <ComKnowledge />
          </div>
          <div v-if="knowledgeView === 'knowledge-control'">
            <knowledgeControl />
          </div>
        </div>

        <!-- 新增：我的收藏菜单内容 -->
        <div v-if="activeMenu === 'collection'">
          <div v-if="collectionView === 'knowledge-collection'">
            <KnowledgeCollection />
          </div>
          <div v-if="collectionView === 'learning-materials'">
            <learningCollection />
          </div>
        </div>

        <!-- 面试日历-->
        <InterviewRecord v-if="activeMenu === 'record'" />

        <schedule v-if="activeMenu === 'schedule'" />

        <!-- 账号设置 -->
        <div v-if="activeMenu === 'account'">
          <el-tabs v-model="activeTab" class="profile-tabs">
            <el-tab-pane label="个人资料" name="user">
              <UserInfo ref="user" :user='user' v-if="visible.user" />
            </el-tab-pane>
            <el-tab-pane label="修改密码" name="password">
              <Password ref="password" v-if="visible.password" />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import OSS from 'ali-oss'
import MainContent from './components/MainContent.vue'
import { UserSettingInfo, UpdateAvatar } from '@/api/permission/userSetting'
import UserInfo from '../../basic/profile/components/UserInfo'
import Password from '../../basic/profile/components/Password'
import InterviewRecord from '../../basic/profile/components/interviewrecord'
import InterviewAbility from '../../basic/profile/components/interviewability'
import ResumeList from '../../basic/profile/components/resume.vue'
import Community from '../../main/community/community.vue'
import Try from '../../basic/profile/components/try.vue'
import ComKnowledge from '../community/whu_comknowledge/index.vue'
import KnowledgeBase from '../community/whu_knowledgebase/index.vue'
import KnowledgeCollection from '../community/whu_knowledgecollection/index.vue'
import learningCollection from '../community/whu_learningcollection/index.vue'
import knowledgeControl from '../community/document/index.vue'
import schedule from './schedule/index.vue'
import ResumeSDK from '../../basic/profile/components/resumeSDK.vue'


export default {
  name: 'App',
  components: {
    MainContent,
    UserInfo,
    Password,
    InterviewRecord,
    InterviewAbility,
    ResumeList,
    Community,
    Try,
    ComKnowledge,
    KnowledgeBase,
    KnowledgeCollection,
    learningCollection,
    knowledgeControl,
    schedule,
    ResumeSDK
  },
  data() {
    return {
      user: {
        realName: '芒果',
        avatar: '',
        signature: '冲击算法岗！'
      },
      activeMenu: 'community', // 默认显示MainContent
      // 我的简历子按钮
      resumeView: '简历版本管理',
      resumeSubTabs: [
        { name: 'resume-sdk', label: '简历解析/画像/润色' },
        { name: 'resume-manage', label: '简历版本管理' }
      ],
      // 新增：知识库子按钮
      knowledgeView: 'personal-knowledge',
      knowledgeSubTabs: [
        { name: 'personal-knowledge', label: '个人知识库' },
        { name: 'community-knowledge', label: '社区知识库' },
        { name: 'knowledge-control', label: '知识管理' }
      ],
      // 新增：我的收藏子按钮
      collectionView: 'knowledge-collection',
      collectionSubTabs: [
        { name: 'knowledge-collection', label: '知识库' },
        { name: 'learning-materials', label: '学习资料' }
      ],
      activeTab: 'user',
      visible: {
        user: true,
        password: false
      },
      uploadHeaders: {
        Authorization: `Bearer ${localStorage.getItem('token') || ''}`
      },
      ossConfig: {
        region: 'oss-cn-wuhan-lr',
        accessKeyId: 'LTAI5tE1sjS9v6rVPid3HXzr',
        accessKeySecret: 'd3dCLmg0CBQgMX5fbSjZc6qMPWJcMj',
        bucket: 'mangopdf',
        endpoint: 'https://mangopdf.oss-cn-wuhan-lr.aliyuncs.com'
      },
      resumeSDKData: null,
      resumeSDKPaint: null
    }
  },
  computed: {
    avatarUrl() {
      if (!this.user.avatar) return '';

      // 如果已经是完整URL则直接返回
      if (this.user.avatar.startsWith('http')) {
        return this.user.avatar;
      }

      // 处理后端返回的API路径格式
      if (this.user.avatar.startsWith('/api/file/Image/userAvatar/')) {
        const filename = this.user.avatar.split('/').pop();
        return `${this.ossConfig.endpoint}/avatars/${filename}`;
      }

      // 默认处理其他情况
      return this.user.avatar.startsWith('avatars/')
        ? `${this.ossConfig.endpoint}/${this.user.avatar}`
        : `${this.ossConfig.endpoint}/avatars/${this.user.avatar}`;
    }
  },
  watch: {
    activeTab(val) {
      for (let key of Object.keys(this.visible)) {
        this.visible[key] = false
      }
      this.visible[val] = true
    }
  },
  created() {
    this.fetchUserInfo()
  },
  methods: {
    selectMenu(menu) {
      this.activeMenu = menu
      // 切换到"我的简历"时默认选中第一个子项
      if (menu === 'resume') this.resumeView = this.resumeSubTabs[0].name
      // 切换到"知识库"时默认选中第一个子项
      if (menu === 'knowledge') this.knowledgeView = 'personal-knowledge'
      // 切换到"我的收藏"时默认选中第一个子项
      if (menu === 'collection') this.collectionView = 'knowledge-collection'
      // 切换到账号设置时默认tab
      if (menu === 'account') this.activeTab = 'user'
    },
    // 获取用户信息
    fetchUserInfo() {
      UserSettingInfo().then(res => {
        this.user = res.data || this.user
      }).catch(err => {
        console.error('获取用户信息失败', err)
      })
    },
    async handleAvatarUpload(file) {
      try {
        this.loading = true;

        // 验证文件
        const rawFile = file.raw;
        if (!rawFile) {
          throw new Error('未选择文件');
        }

        // 1. 初始化华为云OSS客户端
        const client = new OSS({
          region: this.ossConfig.region,
          accessKeyId: this.ossConfig.accessKeyId,
          accessKeySecret: this.ossConfig.accessKeySecret,
          bucket: this.ossConfig.bucket
        });

        // 2. 生成唯一文件名
        const extension = rawFile.name.split('.').pop();
        const fileName = `avatars/${Date.now()}.${extension}`;

        // 3. 上传到OSS
        const result = await client.put(fileName, rawFile);

        // 4. 获取文件URL
        const avatarUrl = result.url;

        // 5. 更新用户头像
        const afile = avatarUrl.split('/').pop();
        await this.updateAvatar(afile);

        this.$message.success('头像上传成功');
      } catch (error) {
        console.error('头像上传失败:', error);
        this.$message.error('头像上传失败');
      } finally {
        this.loading = false;
      }
    },
    async updateAvatar(fileName) {
      try {
        await UpdateAvatar(fileName);
        this.fetchUserInfo();
      } catch (error) {
        console.error('头像更新失败:', error);
        this.$message.error('头像更新失败');
      }
    },

    // 任务点击处理
    handleTask(taskType) {
      console.log(`处理 ${taskType} 任务`)
    },
    // 由子组件直接调用
    showResumeAnalysis(analysis, paint) {
      // 切换到“我的简历”
      this.activeMenu = 'resume';
      // 切换到“简历解析/画像/润色”子视图
      this.resumeView = 'resume-sdk';
      // 把数据给 ResumeSDK
      this.resumeSDKData = analysis;
      this.resumeSDKPaint = paint;
      console.log("Received analysis:", analysis);
      console.log("Received paint:", paint);
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: rgb(80, 73, 44);
}

.container {
  display: flex;
  min-height: 100vh;
  background-color: rgb(255, 250, 240);
}

.sidebar {
  width: 210px;
  background: linear-gradient(135deg, #f9f7f2 0%, #f6f3ea 100%);
  padding: 18px 10px 18px 10px;
  box-sizing: border-box;
  border-radius: 16px;
  margin: 24px 0 24px 24px;
  box-shadow: 0 2px 12px 0 rgba(200, 180, 120, 0.08);
  border: 1px solid #f0e6d2;
}

.profile {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  background: #f7f5f0;
  border-radius: 12px;
  padding: 12px 10px;
  box-shadow: 0 2px 8px 0 rgba(200, 180, 120, 0.06);
}

.avatar-container {
  position: relative;
}

.avatar-box {
  position: relative;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 12px;
  border: 2px solid #f0e6d2;
  box-shadow: 0 1px 4px 0 rgba(200, 180, 120, 0.08);
  background: #f6f3ea;
}

.avatar-hover {
  position: absolute;
  left: 0;
  top: 0;
  font-size: 12px;
  display: none;
  width: 50px;
  height: 50px;
  text-align: center;
  border-radius: 50%;
  line-height: 50px;
  color: #fff;
  cursor: pointer;
  background: rgba(0, 0, 0, 0.5);
}

.avatar-uploader:hover .avatar-hover {
  display: block;
}

.info .username {
  margin: 0;
  font-size: 17px;
  font-weight: 600;
  color: #a68c5a;
  letter-spacing: 1px;
}

.info .motto {
  margin: 0;
  font-size: 13px;
  color: #b8ad98;
  margin-top: 4px;
  font-weight: 400;
  letter-spacing: 0.3px;
}

.custom-menu {
  margin-bottom: 18px;
  width: 100%;
}

.menu-btn {
  width: 100%;
  padding: 11px 0 11px 20px;
  margin-bottom: 8px;
  text-align: left;
  background: #f6f3ea;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.18s cubic-bezier(.4, 0, .2, 1);
  display: flex;
  align-items: center;
  font-size: 15px;
  color: #a68c5a;
  font-weight: 500;
  box-shadow: 0 1px 4px 0 rgba(200, 180, 120, 0.06);
  position: relative;
  letter-spacing: 0.3px;
}

.menu-btn.active {
  background: #f3e7c9;
  color: #bfa76a;
  font-weight: 700;
  box-shadow: 0 2px 8px 0 rgba(200, 180, 120, 0.13);
}

.menu-btn:hover {
  background: #f3e7c9;
  color: #bfa76a;
}

.sub-btn {
  width: 100%;
  padding: 8px 0 8px 32px;
  margin-bottom: 6px;
  font-size: 14px;
  color: #b8ad98;
  background: #f6f3ea;
  cursor: pointer;
  transition: background 0.18s, color 0.18s;
  border-radius: 6px;
  border: none;
  letter-spacing: 0.1px;
}

.sub-btn.active {
  background: linear-gradient(90deg, #f3e7c9 0%, #e8d7b1 100%);
  color: #fff;
  font-weight: 600;
}

.task-recommend h3 {
  margin-bottom: 10px;
  font-size: 14px;
}

.task-recommend ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.task-recommend li {
  padding: 8px 0;
  cursor: pointer;
  color: #007bff;
  transition: color 0.3s ease;
}

.task-recommend li:hover {
  color: #0056b3;
}

.main-content {
  flex: 1;
  padding: 20px;
}
</style>
